Manon.icu

I'm here to make you a better developer by teaching you everything I know about building for the web.

Published 2022-05-21

Next.js - Shallow Routing

浅路由是在同一个路由中跳转,不会调用数据获取函数,比如:getServerSidePropsgetStaticProps等。

启用浅路由的方式,在路由跳转中设置shallowtrue

import Router from 'next/router'
import Head from 'next/head'

function HomePage(props) {
  return (
    <>
      <Head>
        <title>Welcome to Next.js!</title>
      </Head>
      <div>Welcome to Next.js!</div>
      <span
        onClick={() => Router.push('/?counter=1', undefined, {shallow: true})}
      >
        Reload
      </span>
      <br />
      <div>Next stars: {props.stars}</div>
      <img src="/logo.png" alt="Logo" />
    </>
  )
}

export async function getServerSideProps(context) {
  const res = await fetch('https://api.github.com/repos/vercel/next.js')
  const json = await res.json()
  return {
    props: {stars: json.stargazers_count}
  }
}

export default HomePage

上面的代码仅接收路由的参数更新,且不会被替换。

Comments

No Comments!